//
//  UserManager.m
//  FinanceBBS
//
//  Created by mibo02 on 2017/12/15.
//  Copyright © 2017年 mibo02. All rights reserved.
//

#import "UserManager.h"
#import "FoundModel.h"

@interface UserManager () 

@end
@implementation UserManager
SINGLETON_FOR_CLASS(UserManager);

-(instancetype)init{
    self = [super init];
    if (self) {
        //被踢下线
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(onKick:)
                                                     name:KNotificationOnKick
                                                   object:nil];
    }
    return self;
}

#pragma mark ————— 自动登录到服务器 —————
-(void)autoLoginToServer:(loginBlock)completion{
    [self autoGetUserInformation:completion];
}
- (void)autoGetUserInformation:(loginBlock)completion{
   
}
#pragma mark ————— 登录成功处理 —————
-(void)LoginSuccess:(id )responseObject completion:(loginBlock)completion{
    if (ValidDict(responseObject)) {
        self.curUserInfo = [UserInfo modelWithDictionary:responseObject];
        NSLog(@"im_account %@ im_token%@",self.curUserInfo.im_account,self.curUserInfo.im_token);
        [[[NIMSDK sharedSDK] loginManager]login:self.curUserInfo.im_account token:self.curUserInfo.im_token completion:^(NSError * _Nullable error) {
            if (error) {
                DLog(@"聊天登录失败%@",error.description);
                !completion?:completion(NO,0,error.description);
            }else{
                !completion?:completion(YES,0,XLocalized(@"登录成功!"));
            }
        }];
        [self saveUserInfo];
    }else{
        if (completion) {
            completion(NO,0,XLocalized(@"登录返回数据异常"));
        }
    }
}

#pragma mark ————— 储存用户信息 —————
-(void)saveUserInfo{
    if (self.curUserInfo) {
        self.isLogined = YES;
        YYCache *cache = [[YYCache alloc]initWithName:KUserCacheName];
        NSDictionary *dic = [self.curUserInfo modelToJSONObject];
        [cache setObject:dic forKey:KUserModelCache];
    }
    
}
#pragma mark ————— 加载缓存的用户信息 —————
-(BOOL)loadUserInfo{
    YYCache *cache = [[YYCache alloc]initWithName:KUserCacheName];
    NSDictionary * userDic = (NSDictionary *)[cache objectForKey:KUserModelCache];
    if (userDic) {
        self.curUserInfo = [UserInfo modelWithDictionary:userDic];
        self.isLogined = YES;
        return YES;
    }
    return NO;
}
#pragma mark ————— 被踢下线 —————
-(void)onKick:(NSNotification*)noti{
    NSString *notiStr = noti.object;
    [self logout:^(BOOL success, NSString *des) {
        if (success) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [XAlertTool alertTitle:XLocalized(@"温馨提示") message:notiStr cancelAction:nil sureAction:^{
                    [kCurrentVC.navigationController popToRootViewControllerAnimated:YES];
                }];
            });
            
        }
    }];
}
#pragma mark ————— 退出登录 —————
- (void)logout:(void (^)(BOOL success, NSString *des))completion{
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
//    [[UIApplication sharedApplication] unregisterForRemoteNotifications];
//    [UMessage removeAlias:kCurUser.push_alias  type:@"" response:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
//        if (responseObject) {
//            if ([[responseObject objectForKey:@"success"] isEqualToString:@"ok"]) {
//                DLog(@"删除别名成功");
//            }else
//            {
//
//            }
//        }else
//        {
//
//        }
//    }];
    self.curUserInfo = nil;
    self.isLogined = NO;
    //    //移除缓存
    YYCache *cache = [[YYCache alloc]initWithName:KUserCacheName];
    [cache removeAllObjects];
    [cache removeAllObjectsWithBlock:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (completion) {
                completion(YES,nil);
                KPostNotification(KNotificationLoginStateChange, @NO);
            }
        });
    }];
}

- (void)saveSeachWord:(NSString *)word{
    YYCache *cache = [[YYCache alloc]initWithName:kHistroySearchWordCacheKey];
    NSArray * words = (NSArray *)[cache objectForKey:kHistroySearchWordCacheKey];
    if (!words) {
        words=@[];
    }
    NSMutableArray*mWords = words.mutableCopy;
    if (![mWords containsObject:word]) {
        [mWords insertObject:word atIndex:0];
    }else{
        [mWords removeObject:word];
        [mWords insertObject:word atIndex:0];
    }
    [cache setObject:mWords forKey:kHistroySearchWordCacheKey];
}
- (NSArray *)haveSearchWords{
    YYCache *cache = [[YYCache alloc]initWithName:kHistroySearchWordCacheKey];
    NSArray * words = (NSArray *)[cache objectForKey:kHistroySearchWordCacheKey];
    return words;
}
- (void)clearSearchWords{
    YYCache *cache = [[YYCache alloc]initWithName:kHistroySearchWordCacheKey];
    [cache removeAllObjects];
}

- (void)saveGroupSeachWord:(NSString *)word{
    YYCache *cache = [[YYCache alloc]initWithName:kHistroySearchGroupWordCacheKey];
    NSArray * words = (NSArray *)[cache objectForKey:kHistroySearchGroupWordCacheKey];
    if (!words) {
        words=@[];
    }
    NSMutableArray*mWords = words.mutableCopy;
    if (![mWords containsObject:word]) {
        [mWords insertObject:word atIndex:0];
    }else{
        [mWords removeObject:word];
        [mWords insertObject:word atIndex:0];
    }
    [cache setObject:mWords forKey:kHistroySearchGroupWordCacheKey];
}
- (NSArray *)haveGroupSearchWords{
    YYCache *cache = [[YYCache alloc]initWithName:kHistroySearchGroupWordCacheKey];
    NSArray * words = (NSArray *)[cache objectForKey:kHistroySearchGroupWordCacheKey];
    return words;
}
- (void)clearGroupSearchWords{
    YYCache *cache = [[YYCache alloc]initWithName:kHistroySearchGroupWordCacheKey];
    [cache removeAllObjects];
}

- (void)saveRecentlyUsed:(FoundRecommendModel*)dapp{
    YYCache *cache = [[YYCache alloc]initWithName:kRecentlyUsedCacheKey];
    NSMutableArray*mjsons = [NSMutableArray arrayWithArray:[self getRecentlyUsed]];
   __block BOOL isHave;
    [mjsons enumerateObjectsUsingBlock:^(FoundRecommendModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.modelId isEqualToString:dapp.modelId]) {
            [mjsons removeObject:obj];
            [mjsons insertObject:dapp atIndex:0];
            *stop = YES;
            isHave = YES;
        }
    }];
    if (!isHave) {
        [mjsons insertObject:dapp atIndex:0];
    }
    [cache setObject:[mjsons modelToJSONObject] forKey:kRecentlyUsedCacheKey];
}
- (NSArray <FoundRecommendModel*>*)getRecentlyUsed{
    YYCache *cache = [[YYCache alloc]initWithName:kRecentlyUsedCacheKey];
    return [NSArray modelArrayWithClass:[FoundRecommendModel class] json:[cache objectForKey:kRecentlyUsedCacheKey]];
}

- (void)saveDappAggreeId:(NSString *)dappId{
    YYCache *cache = [[YYCache alloc]initWithName:kAgreeDappIdsKey];
    NSArray * dappIds = (NSArray *)[cache objectForKey:kAgreeDappIdsKey];
    NSMutableArray*mdappIds = [NSMutableArray arrayWithArray:dappIds?:@[]];
    if (![mdappIds containsObject:dappId]) {
        [mdappIds addObject:dappId];
    }
    [cache setObject:mdappIds forKey:kAgreeDappIdsKey];
}

- (NSArray *)haveDappAggreeId{
    YYCache *cache = [[YYCache alloc]initWithName:kAgreeDappIdsKey];
    NSArray * dappIds = (NSArray *)[cache objectForKey:kAgreeDappIdsKey];
    return dappIds?:@[];
}
@end
